package com.example.spring5demo;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class CompleteFutureDemo {


    public static void main(String[] args) {


        List<Integer> list2 = new ArrayList<Integer>();
        ExecutorService exs = new ThreadPoolExecutor(4, 4,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        List<Person> taskList = Lists.newArrayList();
        for (int i = 1; i <5 ; i++) {
            taskList.add(new Person(i));
        }

        @SuppressWarnings("rawtypes")
        CompletableFuture[] cfs = taskList.stream().map(t -> CompletableFuture.supplyAsync(() -> calc(t), exs)
             //   .thenApply(h -> Integer.toString(h))
                .whenComplete((Person v) -> {//如需获取任务完成先手顺序，此处代码即可
                   if(v instanceof Person){

                   }
                    list2.add(v);
                }))
                .toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(cfs).join();//封装后无返回值，必须自己whenComplete()获取
        System.out.println("list2=" + list2   );
    }

    public static Integer calc(Person p) {
        try {
            int i =p.getId();
            if (i == 1) {
                Thread.sleep(3000);//任务1耗时3秒
            } else if (i == 2) {
                Thread.sleep(5000);//任务5耗时5秒
            }else if (i == 3) {
                Thread.sleep(500);//任务5耗时5秒
            } else {
                Thread.sleep(1000);//其它任务耗时1秒
            }
            System.out.println("task线程：" + Thread.currentThread().getName() + "任务i=" + i + ",完成！+" + new Date());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return i;
    }

}
